/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.NamespaceContextImpl;
import global.sandbox.xmlutilities.XMLTools;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class XPathEvaluation {
    
    final static NamespaceContext namespaces;
    
    static {
        final NamespaceContextImpl nspaces = new NamespaceContextImpl();
        nspaces.addNamespace(
                "ns",
                "http://hadrabap.googlepages.com/projects/xmlutilities/demo");
        
        namespaces = nspaces;
    }
    
    public static Attr loadAttribute(Element rootNode, String xPathQuery)
            throws XPathEvaluationException {
        Node node;
        try {
            node = XMLTools.getFirstNodeForXPath(
                    xPathQuery,
                    rootNode,
                    namespaces);
        } catch (Exception ex) {
            throw new XPathEvaluationException(ex);
        }
        
        if (node == null) {
            return null;
        }
        
        if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            return (Attr) node;
        } else {
            throw new XPathEvaluationException(
                    "Resulting node is not Attr, gotten "
                    + node.getNodeType());
        }
    }
    
    public static class XPathEvaluationException extends Exception {
        
        private static final long serialVersionUID = 1L;
        
        public XPathEvaluationException(String message) {
            super(message);
        }
        
        public XPathEvaluationException(Throwable cause) {
            super(cause);
        }
        
    }
    
}
